package com.example.zhangwei.widgts.refreshlist;

import java.text.SimpleDateFormat;

import com.example.zhangwei.R;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.DecelerateInterpolator;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Scroller;
import android.widget.TextView;

/**
 * 下来刷新
 */
public class FreshLayout extends LinearLayout 
{
    private Context mContext;
    
    private PullToRfreshListener mPullToRfreshListener;
    
    private PullToRefreshListViewHeader mHeaderView;
    
    private RelativeLayout mHeaderViewContent;
    
    private TextView mHeaderTimeView;
    
    private long refreshTime = 0;
    
    private int mHeaderViewHeight;
    
    private final static int SCROLL_DURATION = 400;
    private final static float OFFSET_RADIO = 1.8f;
    
    private static final int LAST_REFRESH_TIME = 800;
    
    private boolean mPullRefreshing = false;
    
    private String timeTag = "";
    
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm");
    
    private float DownY = -1;
    
    private Scroller mScroller;
    
	public FreshLayout(Context context) 
	{
		super(context);
		// TODO Auto-generated constructor stub
		mContext = context;
		initHeadView(context);
		mScroller = new Scroller(context, new DecelerateInterpolator());
	}
	
	public FreshLayout(Context context, AttributeSet attrs) 
	{
		super(context, attrs);
		// TODO Auto-generated constructor stub
		mContext = context;
		initHeadView(context);
		mScroller = new Scroller(context, new DecelerateInterpolator());
	}
	
	public void setPullToRfreshListener(PullToRfreshListener l)
	{
	    mPullToRfreshListener = l;
	}
	
	private void initHeadView(Context context)
	{
	    mHeaderView = new PullToRefreshListViewHeader(context);
        mHeaderViewContent = (RelativeLayout) mHeaderView.findViewById(R.id.xlistview_header_content);
        mHeaderTimeView = (TextView) mHeaderView.findViewById(R.id.xlistview_header_time);

        // init header height
        mHeaderView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener()
        {
            @Override
            public void onGlobalLayout()
            {
                mHeaderViewHeight = mHeaderViewContent.getHeight();
                getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });
        
        this.addView(mHeaderView);
	}
	
	private void updateHeaderHeight(float delta)
    {
        mHeaderView.setVisiableHeight((int) delta + mHeaderView.getVisiableHeight());
        if (!mPullRefreshing)
        { // 未处于刷新状态，更新箭头
            if (mHeaderView.getVisiableHeight() > mHeaderViewHeight)
            {
                mHeaderView.setState(PullToRefreshListViewHeader.STATE_READY);
            }
            else
            {
                mHeaderView.setState(PullToRefreshListViewHeader.STATE_NORMAL);
            }
        }
    }
	
	public void stopRefresh()
    {
        if (mPullRefreshing == true)
        {
            mPullRefreshing = false;
            long times = System.currentTimeMillis() - refreshTime;
            if (times >= LAST_REFRESH_TIME)
            {
                resetHeaderHeight();
                changeRefreshTime();
            }
            else
            {
                new Handler().postDelayed(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        resetHeaderHeight();
                        changeRefreshTime();
                    }
                }, LAST_REFRESH_TIME - times);
            }
        }
    }
	
	private void changeRefreshTime()
    {
        // 2 重置刷新时间
        setRefreshTime();
        String last = getLastRefreshTime();
        mHeaderTimeView.setText(last);
    }
	
	private void setRefreshTime()
    {
        long currentTime = System.currentTimeMillis();
//        PreferencesUtils.setPreferences(mContext, "PullToRefresh", timeTag, currentTime);

    }

    private String getLastRefreshTime()
    {
//        long lastRefreshTime = PreferencesUtils.getPreference(mContext, "PullToRefresh", timeTag,
//                System.currentTimeMillis());
        String time = dateFormat.format(System.currentTimeMillis());
        return time;
    }

    /**
     * reset header view's height.
     */
    private void resetHeaderHeight()
    {
        int height = mHeaderView.getVisiableHeight();
        if (height == 0) // not visible.
            return;
        // refreshing and header isn't shown fully. do nothing.
        if (mPullRefreshing && height <= mHeaderViewHeight)
        {
            return;
        }
        int finalHeight = 0; // default: scroll back to dismiss header.
        // is refreshing, just scroll back to show all the header.
        if (mPullRefreshing && height > mHeaderViewHeight)
        {
            finalHeight = mHeaderViewHeight;
        }
        
        mScroller.startScroll(0, height, 0, finalHeight - height, SCROLL_DURATION);
        invalidate();
    }
	
	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		if (DownY == -1)
		{
			DownY = event.getRawY();
		}
		
		switch (event.getAction())
		{
		case MotionEvent.ACTION_DOWN:
			DownY = event.getRawY();
			return true;
		case MotionEvent.ACTION_MOVE:
			float deltaY = event.getRawY() - DownY;
			DownY = event.getRawY();
			if (deltaY > 0)
			{
			    updateHeaderHeight(deltaY / OFFSET_RADIO);
			}
			break;
		default:		
		    if (!mPullRefreshing && mHeaderView.getVisiableHeight() > mHeaderViewHeight)
            {
                mPullRefreshing = true;
                mHeaderView.setState(PullToRefreshListViewHeader.STATE_REFRESHING);
                if (mPullToRfreshListener != null)
                {
                    refreshTime = System.currentTimeMillis();
                    mPullToRfreshListener.onRefresh();
                }
            }
            resetHeaderHeight();
			break;
		}
		
		return super.onTouchEvent(event);
	}
	
	
	@Override
    public void computeScroll()
    {
        if (mScroller.computeScrollOffset())
        {
            mHeaderView.setVisiableHeight(mScroller.getCurrY());
			
            postInvalidate();
        }
        super.computeScroll();
    }
	

	public interface PullToRfreshListener
	{
	    public void onRefresh();
	}
}
